package com.shuda.business.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuda.business.channel.entity.DataPoolEntity;
import com.shuda.business.channel.mapper.DataPoolMapper;
import com.shuda.business.channel.mapper.DataPoolDataMapper;
import com.shuda.business.channel.service.DataPoolService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.PageResult;
import com.shuda.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据池服务实现类
 */
@Service
public class DataPoolServiceImpl implements DataPoolService {

    private final DataPoolMapper dataPoolMapper;
    private final DataPoolDataMapper dataPoolDataMapper;

    /**
     *
     * DataPoolServiceImpl 构造方法
     * @param dataPoolMapper 数据池Mapper
     * @param dataPoolDataMapper 数据池数据Mapper
     * @return $returns$
     * @author ink
     * @Description: 显式构造注入，移除对Lombok的依赖，确保Spring构造器注入正常工作
     * @date 2025-11-09 23:45
     */
    public DataPoolServiceImpl(DataPoolMapper dataPoolMapper, DataPoolDataMapper dataPoolDataMapper) {
        this.dataPoolMapper = dataPoolMapper;
        this.dataPoolDataMapper = dataPoolDataMapper;
    }

    @Override
    public PageResult<DataPoolEntity> getDataPoolPage(PageDTO pageDTO, QueryWrapper<DataPoolEntity> queryWrapper) {
        // 修正PageDTO的访问：使用getPageNum/getPageSize，保持与DTO定义一致
        Page<DataPoolEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        if (pageDTO.getOrderBy() != null && !pageDTO.getOrderBy().trim().isEmpty()) {
            String orderBy = pageDTO.getOrderBy();
            String orderType = pageDTO.getOrderType();
            if ("desc".equalsIgnoreCase(orderType)) {
                page.setOrders(List.of(com.baomidou.mybatisplus.core.metadata.OrderItem.desc(orderBy)));
            } else {
                page.setOrders(List.of(com.baomidou.mybatisplus.core.metadata.OrderItem.asc(orderBy)));
            }
        }
        
        Page<DataPoolEntity> resultPage = dataPoolMapper.selectPage(page, queryWrapper);
        // 兼容三参构造（records、total、pages）
        return new PageResult<>(resultPage.getRecords(), resultPage.getTotal(), resultPage.getPages());
    }

    @Override
    public DataPoolEntity getById(Long id) {
        return dataPoolMapper.selectById(id);
    }

    @Override
    @Transactional
    public void createDataPool(DataPoolEntity pool) {
        // 检查数据池名称是否已存在
        QueryWrapper<DataPoolEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pool_name", pool.getPoolName());
        if (dataPoolMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("数据池名称已存在");
        }

        // 设置默认值
        pool.setStatus("disabled");
        pool.setDataCount(0);
        pool.setCreateTime(LocalDateTime.now());
        pool.setCreateBy(SecurityUtils.getCurrentUsername());
        
        dataPoolMapper.insert(pool);
    }

    @Override
    @Transactional
    public void updateDataPool(DataPoolEntity pool) {
        // 检查是否存在
        DataPoolEntity existingPool = dataPoolMapper.selectById(pool.getId());
        if (existingPool == null) {
            throw new BusinessException("数据池不存在");
        }

        // 如果修改了数据池名称，检查新名称是否已存在
        if (!existingPool.getPoolName().equals(pool.getPoolName())) {
            QueryWrapper<DataPoolEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pool_name", pool.getPoolName());
            if (dataPoolMapper.selectCount(queryWrapper) > 0) {
                throw new BusinessException("数据池名称已存在");
            }
        }

        pool.setUpdateTime(LocalDateTime.now());
        pool.setUpdateBy(SecurityUtils.getCurrentUsername());
        
        dataPoolMapper.updateById(pool);
    }

    @Override
    @Transactional
    public void deleteDataPool(Long id) {
        DataPoolEntity pool = dataPoolMapper.selectById(id);
        if (pool == null) {
            throw new BusinessException("数据池不存在");
        }

        // 逻辑删除
        pool.setDeleted(1);
        pool.setUpdateTime(LocalDateTime.now());
        pool.setUpdateBy(SecurityUtils.getCurrentUsername());
        dataPoolMapper.updateById(pool);

        // 删除数据池中的数据
        dataPoolDataMapper.deleteByPoolId(id);
    }

    @Override
    @Transactional
    public void deleteDataPools(List<Long> ids) {
        for (Long id : ids) {
            deleteDataPool(id);
        }
    }

    @Override
    @Transactional
    public void updateDataPoolStatus(Long id, String status) {
        DataPoolEntity pool = dataPoolMapper.selectById(id);
        if (pool == null) {
            throw new BusinessException("数据池不存在");
        }

        pool.setStatus(status);
        pool.setUpdateTime(LocalDateTime.now());
        pool.setUpdateBy(SecurityUtils.getCurrentUsername());
        dataPoolMapper.updateById(pool);
    }

    @Override
    public void enableDataPool(Long id) {
        updateDataPoolStatus(id, "enabled");
    }

    @Override
    public void disableDataPool(Long id) {
        updateDataPoolStatus(id, "disabled");
    }

    @Override
    @Transactional
    public void clearDataPool(Long id) {
        DataPoolEntity pool = dataPoolMapper.selectById(id);
        if (pool == null) {
            throw new BusinessException("数据池不存在");
        }

        // 清空数据池中的数据
        int deletedCount = dataPoolDataMapper.deleteByPoolId(id);
        
        // 更新数据池统计信息
        pool.setDataCount(0);
        pool.setUpdateTime(LocalDateTime.now());
        pool.setUpdateBy(SecurityUtils.getCurrentUsername());
        dataPoolMapper.updateById(pool);
    }

    @Override
    public Object getDataPoolStatistics(Long id) {
        DataPoolEntity pool = dataPoolMapper.selectById(id);
        if (pool == null) {
            throw new BusinessException("数据池不存在");
        }

        Map<String, Object> statistics = new HashMap<>();
        statistics.put("poolId", id);
        statistics.put("poolName", pool.getPoolName());
        statistics.put("dataCount", pool.getDataCount());
        statistics.put("poolType", pool.getPoolType());
        statistics.put("status", pool.getStatus());
        
        // 获取数据分布统计
        Map<String, Object> dataDistribution = dataPoolDataMapper.getDataDistribution(id);
        statistics.put("dataDistribution", dataDistribution);
        
        return statistics;
    }

    @Override
    public List<DataPoolEntity> getActiveDataPools() {
        // 仅返回启用且未删除的数据池，按创建时间倒序
        QueryWrapper<DataPoolEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "enabled");
        queryWrapper.eq("deleted", 0);
        queryWrapper.orderByDesc("create_time");
        return dataPoolMapper.selectList(queryWrapper);
    }
}